import React, {useCallback} from 'react';
import {Input, Modal} from 'antd';
import '../styles/subject.scss';
import {useImmerState} from '../hooks/useImmerState';
import ImgUploader from './imgUpload';
import useDidMount from '../hooks/useDidMount';
import {eventBus} from '../helpers/eventBus';

const initialForm = {
  title: '',
  link: '',
  picurl: ''
};

const SubjectEditor = (props) => {

  const {onSubmit} = props;
  const [state, setState] = useImmerState({
    visible: false,
    type: 'edit'
  });
  const [form, setForm] = useImmerState(initialForm);

  const showEditor = subject => {
    setState(() => {
      return {
        visible: true,
        type: subject ? 'edit' : 'add'
      };
    });
    setForm(() => subject || initialForm);
  };

  const hideEditor = useCallback(() => {
    setState(draft => {
      draft.visible = false;
    });
  }, []);

  useDidMount(() => {
    eventBus.on('editSubject', showEditor);
    return () => {
      eventBus.off('editSubject', showEditor);
    };
  });

  return (
    <Modal
      className="subject-editor"
      visible={state.visible}
      title={state.type === 'add' ? '添加课程' : '修改课程'}
      onOk={() => {onSubmit(state.type, form); hideEditor();}}
      onCancel={hideEditor}
    >
      <div className="item">标题：<Input
        placeholder="输入专题标题"
        onChange={e => {
          const val = e.target.value;
          setForm(draft => {
            draft.title = val;
          });
        }}
        value={form.title}/>
      </div>
      <div className="item">封面：
        <ImgUploader
          onUploaded={(imgUrl) => {
            setForm(draft => {
              draft.picurl = imgUrl;
            });
          }}
          logo={form.picurl}
        />
      </div>
      <div className="item">链接：<Input
        placeholder="输入专题链接"
        onChange={e => {
          const val = e.target.value;
          setForm(draft => {
            draft.link = val;
          });
        }}
        value={form.link}/>
      </div>
    </Modal>
  );
};

export default SubjectEditor;